//
//  OrderDetailVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/5.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit

class WriteViewController: UIViewController {

    let bgScr = UIScrollView()
    let priceLab:UILabel = UILabel()
    var tfs:Array<UITextField> = Array()
    var priceInfo:String?
    var stock:StockM?
    var product:ProductVo?
    var subPro:ProductProList?
    var allPrice:String?
    var num1:Int = 0
    var num2:Int = 0


    lazy var goodInfoView:UIView = {
        
        let bg:UIView = UIView()
        bg.backgroundColor = UIColor.white
        bg.sd_cornerRadius = SMALL_BTN_RADIUS

        let titlab = UILabel()
        titlab.text = "产品信息"
        titlab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        titlab.textColor = UIColor.black
        bg.addSubview(titlab)
        
        let _  = titlab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(35)!.topSpaceToView(bg,5)!.rightSpaceToView(bg,16)
        
        
        let nameLab = UILabel()
        nameLab.text = self.product?.pdtName
        nameLab.font =  UIFont.commonFont
        nameLab.textColor = UIColor.black
        bg.addSubview(nameLab)
        
        let _  = nameLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(titlab,10)!.rightSpaceToView(bg,16)
        nameLab.setMaxNumberOfLinesToShow(2)
        
        
        let infoLab = UILabel()
        let date = self.stock?.saleDate?.split(string: "T").first
        infoLab.text = "套餐类型:\(self.subPro!.pdtName!)"
        infoLab.font =  UIFont.commonFontSmaller
        infoLab.textColor = UIColor.init(hexString: "#999999")
        bg.addSubview(infoLab)
        
        let _  = infoLab.sd_layout()?.leftSpaceToView(bg,16)!.autoHeightRatio(0)!.topSpaceToView(nameLab,10)!.rightSpaceToView(bg,16)
        infoLab.setMaxNumberOfLinesToShow(4)
        
        
        let timelab = UILabel()
        timelab.text = "出行时间:\(date!)"
        timelab.font = UIFont.commonFontSmaller
        timelab.textColor = UIColor.init(hexString: "#999999")
        bg.addSubview(timelab)
        let _ = timelab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(20)?.topSpaceToView(infoLab,10)
        timelab.setSingleLineAutoResizeWithMaxWidth(277)
        
        let placelab = UILabel()
        placelab.text = "\(self.product!.basePlace!)出发 \(self.num1)成人 \(self.num2)儿童"
        placelab.font = UIFont.commonFontSmaller
        placelab.textColor = UIColor.init(hexString: "#999999")
        bg.addSubview(placelab)
        let _ = placelab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(20)?.topSpaceToView(timelab,10)
        placelab.setSingleLineAutoResizeWithMaxWidth(177)
        
        bg.setupAutoHeight(withBottomView: placelab, bottomMargin: 16)
        return bg
        
        
    }()
    
    lazy var linkView:UIView = {
        
        let bg:UIView = UIView()
        bg.backgroundColor = UIColor.white
        bg.sd_cornerRadius = SMALL_BTN_RADIUS

        let titlab = UILabel()
        titlab.text = "联系人"
        titlab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        titlab.textColor = UIColor.black
        bg.addSubview(titlab)
        
        let _  = titlab.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(35)!.topSpaceToView(bg,5)!.rightSpaceToView(bg,16)
        
        
        var arr = [["title":"姓名","value":"请填写订单联系人姓名"],
                   ["title":"手机","value":"请输入手机号"],
                   ["title":"邮箱","value":"选填,用于接收合同信息"],
                   ["title":"备注","value":"选填,如有其它特殊要求"],

                  ]
        
        
    
        let linkView  = self.createVeiwWithArray(tits: arr )
       bg.addSubview(linkView)
        let _ = linkView.sd_layout()?.topSpaceToView(bg,40)?.autoHeightRatio(0)?.widthRatioToView(bg,1)
       bg.setupAutoHeight(withBottomView: linkView, bottomMargin: 0)
        
        return bg
        
    }()
    
    lazy var bottomView:UIView = {
        
            let bg = UIView()
            bg.backgroundColor = UIColor.white
            
            let payBtn = UIButton()
            bg.addSubview(payBtn)
            payBtn.addTarget(self, action: #selector(commitClick), for: .touchUpInside)
            payBtn.sd_cornerRadius = LARAGE_BTN_RADIUS
            let _ = payBtn.sd_layout()?.widthIs(164)?.heightIs(LARAGE_BTN_HEIGHT)?.rightSpaceToView(bg,10)?.centerYEqualToView(bg)
            payBtn.gradientBtnMainColor()
            
            let tlab = UILabel()
            tlab.text = "提交订单"
            tlab.font = UIFont.commonFontSmall
            tlab.textColor = UIColor.white
            tlab.textAlignment = .center
            payBtn.addSubview(tlab)
            let _ = tlab.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
            
            let priceBtn = UIButton()
            priceBtn.setTitle("总价:", for: .normal)
            priceBtn.titleLabel?.font = UIFont.commonFont
            priceBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
            priceBtn.addTarget(self, action: #selector(priceInfoClick), for: .touchUpInside)
            bg.addSubview(priceBtn)
            let _ = priceBtn.sd_layout()?.leftSpaceToView(bg,16)?.centerYEqualToView(bg)!.widthIs(125)!.heightIs(35)
            let _ =  priceBtn.titleLabel?.sd_layout()?.leftSpaceToView(priceBtn,0)!.heightIs(20)!.widthIs(45)!.centerYEqualToView(priceBtn)
            
            priceBtn.addSubview(self.priceLab)
            self.priceLab.font = UIFont.commonFont
            self.priceLab.textColor = UIColor.GP_Orange_Color
        self.priceLab.text = self.allPrice
            let _  =  self.priceLab.sd_layout()?.leftSpaceToView(priceBtn,40)!.heightIs(20)!.centerYEqualToView(priceBtn)
            self.priceLab.setSingleLineAutoResizeWithMaxWidth(155)
        
            let icon = UIImageView()
            icon.image = UIImage(named: "向下")
            priceBtn.addSubview(icon)
            let _  =  icon.sd_layout()?.widthIs(16)!.heightIs(16)!.leftSpaceToView(self.priceLab,3)!.bottomSpaceToView(priceBtn,8)
            
        
            
            return bg
        
    }()
    
    
    lazy var topView:UIView = {
        
        let bg = UIView()
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 135+HT_StatusBarAndNavigationBarHeight)
        bg.gradientBtnMainColor()
        
        return bg
        
    }()
    lazy var navView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.clear
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: HT_StatusBarAndNavigationBarHeight)
        let cancelBtn = UIButton()
        cancelBtn.setImage(UIImage(named: "back_white"), for: .normal)
        cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
        cancelBtn.setTitleColor(UIColor.textTitleColor, for: .normal)
        cancelBtn.titleLabel?.font = UIFont.commonFontSmaller
        bg.addSubview(cancelBtn)
        let _ = cancelBtn.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(32)!.widthIs(32)!.topSpaceToView(bg,HT_StatusBarHeight+5)

        
        let titLab = UILabel()
        titLab.font = UIFont.titleFont
        titLab.text = "订单填写"
        titLab.textColor = UIColor.white
        bg.addSubview(titLab)
        titLab.textAlignment = .center
        let _ = titLab.sd_layout()?.widthIs(95)!.heightIs(20)!.centerXEqualToView(bg)!.topSpaceToView(bg,HT_StatusBarHeight+5)

    
        
        
        
        return bg
    }()
    @objc func cancelBtnClick(){
        
        POP(vc: self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        //self.navigationView.setTitle("订单填写")
        
        self.view.addSubview(topView)
        bgScr.backgroundColor = UIColor.clear
        bgScr.showsHorizontalScrollIndicator = false
        view.addSubview(self.bgScr)
        
        self.topView.addSubview(self.navView)

        let _  = bgScr.sd_layout()?.topSpaceToView(view,HT_StatusBarAndNavigationBarHeight+64)!.leftSpaceToView(view,16)!.bottomSpaceToView(view,60+HT_TabbarSafeBottomMargin)!.rightSpaceToView(view,16)
        
        view.addSubview(self.bottomView)
        let _ = bottomView.sd_layout()?.widthRatioToView(view,1)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin)!.heightIs(60)
       

        self.bgScr.addSubview(self.goodInfoView)
        let _ = goodInfoView.sd_layout()?.widthRatioToView(self.bgScr,1)?.autoHeightRatio(0)?.topSpaceToView(self.bgScr,0)
        
        
        self.bgScr.addSubview(self.linkView)
        let _ = linkView.sd_layout()?.widthRatioToView(self.bgScr,1)?.autoHeightRatio(0)?.topSpaceToView(goodInfoView,10)
        
        
        let warnStr = "点击“提交订单”，即表示已阅读并同意 <好去处旅游协议> <旅游安全须知>"
        let ixLab = IXAttributeTapLabel()
        self.bgScr.addSubview(ixLab)
        let _ = ixLab.sd_layout()?.leftSpaceToView(bgScr,13)!.rightSpaceToView(bgScr,13)!.autoHeightRatio(0)!.topSpaceToView(self.linkView,10)
        ixLab.backgroundColor = UIColor.clear
        ixLab.setMaxNumberOfLinesToShow(2)
        ixLab.tapBlock = {str in
            
            print("\(str ?? "null")")
            
            if str?.contains("旅游协议") == true {
                
                let webvc = WebViewController()
                webvc.isWord = true
                webvc.myTitle = "好去处旅游协议"
                let url = Bundle.main.path(forResource: "协议", ofType: "doc")
                webvc.url = url!
                PUSH(from: self, to: webvc)
                
            }else{
                
                let webvc = WebViewController()
                webvc.isWord = true
                webvc.myTitle = "旅游安全须知"
                let url = Bundle.main.path(forResource: "安全须知", ofType: "doc")
                webvc.url = url!
                PUSH(from: self, to: webvc)
            }
            
        }
        let model1 = IXAttributeModel()
        model1.range = (warnStr as NSString).range(of: "<好去处旅游协议>")
        model1.string = "<好去处旅游协议>"
        model1.attributeDic = [NSAttributedString.Key.foregroundColor:UIColor.GP_Blue_Color]
        
        self.bgScr.setupAutoContentSize(withBottomView: ixLab, bottomMargin: 0)

        let model2 = IXAttributeModel()
        model2.range = (warnStr as NSString).range(of: "<旅游安全须知>")
        model2.string = "<旅游安全须知>"
        model2.attributeDic = [NSAttributedString.Key.foregroundColor:UIColor.GP_Blue_Color]
        
        ixLab.setText(warnStr, attributes: [NSAttributedString.Key.foregroundColor:UIColor.textPlaceHolderColor,NSAttributedString.Key.font:UIFont.smallerFont], tapStringArray: [model1,model2])
        
        self.bgScr.setupAutoContentSize(withBottomView: ixLab, bottomMargin: 16)
    }
    

    
    func createVeiwWithArray(tits:Array<Dictionary<String,String>>) -> UIView{
        
        let bg = UIView()
        
    
        
        var temp = Array<UIView>()
        
        for index in 0 ..< tits.count{
            
            let dic = tits.get(at: index)
            let cell = self.createContentCellWith(for: dic!, tag: index+1000)
            bg.addSubview(cell)
            
            let  _ = cell.sd_layout()?.heightIs(46.5)

            temp.append(cell)
        }
        
        bg.setupAutoMarginFlowItems(temp, withPerRowItemsCount: 1, itemWidth: self.view.width, verticalMargin: 0, verticalEdgeInset: 0, horizontalEdgeInset: 0)
        
        return bg
    }
    
    func createContentCellWith(for dic:Dictionary<String,String>,tag:Int) -> UIView{
        
        let bg = UIView()
        let titLab = UILabel()
        bg.addSubview(titLab)
        titLab.font = UIFont.commonFontSmaller
        titLab.textColor = UIColor.init(hexString: "#999999")
        titLab.text  = dic["title"]
        let _ =  titLab.sd_layout()?.leftSpaceToView(bg,16)?.heightIs(20)?.widthIs(95)?.centerYEqualToView(bg)
        

        
        
        let valueLab = UITextField()
        tfs.append(valueLab)
        bg.addSubview(valueLab)
        valueLab.placeholder =  dic["value"]
        valueLab.font = UIFont.commonFont
        valueLab.textColor = UIColor.textTitleColorBlack
        let _ =  valueLab.sd_layout()?.leftSpaceToView(titLab,16)?.heightIs(20)?.rightSpaceToView(bg,16)?.centerYEqualToView(bg)
        
        if titLab.text == "手机" {
            
            valueLab.text  = SPUtil.init().mobile
        }
        
        let line = UIView()
        bg.addSubview(line)
        line.backgroundColor = UIColor.lineColor
        let _ = line.sd_layout()?.widthRatioToView(bg,1)?.heightIs(1)?.bottomSpaceToView(bg,0)
        
        
        return bg
    }
    
    
    @objc func commitClick(){
        
        if SPUtil.init().loginStatus == 0{
            
            APP.backToVC = self
            PUSH(from: self, to: LoginViewController())
            return
        }
        if SPUtil.init().mobile.count==0 {
            
            APP.backToVC = self
            PUSH(from: self, to: BindPhoneVC())
            return
        }
        
        let nametf = tfs[0]
        let phonetf = tfs[1]
        let emailtf = tfs[2]
        let marktf = tfs[3]
        if nametf.text?.isEmpty == true {
            
            ToastUtil.show(msg: "请输入姓名")
            return
        }
        if phonetf.text?.phoneValidate == false {
            
            ToastUtil.show(msg: "请输入有效的手机号")
            return
        }
        var params = Dictionary<String,String>()
        
        if emailtf.text!.count > 0 {
            
            if emailtf.text?.emailValidate == false {
                
                ToastUtil.show(msg: "请输入有效的邮箱")
                return
            }
            
            params["email"] = emailtf.text
        }
        
        if marktf.text!.count > 0 {
            params["remark"] = marktf.text

        }
        params["linkName"] = nametf.text
        params["mobile"] = phonetf.text
        params["pdtId"] = self.subPro?.pdtId
        params["proId"] = self.subPro?.id
        params["travelDate"] = self.stock?.saleDate?.split(string: "T").first
        params["price"] = String(format: "%.2f", self.stock!.adultPrice*Float(self.num1) + self.stock!.childPrice*Float(self.num2))
        params["pdtImg"] = self.product?.pdtImg
        if self.num1 >  0 {
            
            params["adultNum"] =  self.num1.description
        }
        if self.num2 >  0 {
            
            params["childNum"] =  self.num2.description
        }
        if self.num1 == 0 && self.num2==0 {
            
            ToastUtil.show(msg: "请选择出行人数")
            return
        }
        
        API.maekOrder(params: params) { (result) in
            
            let order  = result as! OrderVo
            let payVC = PayViewController()
            payVC.order = order
            PUSH(from: self, to: payVC)
        }



    }
    let pricebg = UIView()
    @objc func priceInfoClick() {
         
         self.view.addSubview(pricebg)
         let _  = pricebg.sd_layout()?.spaceToSuperView(.zero)

         let bgImgv = UIImageView()
         bgImgv.alpha = 0.5
         bgImgv.backgroundColor = UIColor.init(patternImage: UIImage(named: "paybg")!)
         pricebg.addSubview(bgImgv)
         let _ = bgImgv.sd_layout()?.spaceToSuperView(.zero)
         
         let bg2 = UIView()
         bg2.backgroundColor = UIColor.white
         pricebg.addSubview(bg2)
         let _ = bg2.sd_layout()?.bottomSpaceToView(pricebg,HT_TabbarSafeBottomMargin)?.widthRatioToView(pricebg,1)?.heightIs(195)
        
        
        
        
        
        let bg = UIView()
        bg2.addSubview(bg)
        let _ = bg.sd_layout()?.heightIs(64)!.widthRatioToView(bg2,1)!.bottomSpaceToView(bg2,0)
        let line = UIView()
        line.backgroundColor = UIColor.lineColor
        bg.addSubview(line)
        let _ = line.sd_layout()?.topSpaceToView(bg,0)!.heightIs(1)!.widthRatioToView(bg,1)
        
        let titlab = UILabel()
        titlab.text = "费用明细"
        titlab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        titlab.textColor = UIColor.black
        titlab.textAlignment = .center
        bg2.addSubview(titlab)
        let _  = titlab.sd_layout()?.centerXEqualToView(bg2)!.heightIs(20)!.topSpaceToView(bg2,16)!.widthIs(95)
        
        
        let aduLab = UILabel()
        aduLab.text = "成人"
        aduLab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        aduLab.textColor = UIColor.init(hexString: "#999999")
        bg2.addSubview(aduLab)
        let _  = aduLab.sd_layout()?.leftSpaceToView(bg2,56)!.heightIs(20)!.topSpaceToView(bg2,60)!.widthIs(45)
        
        let aduValueLab = UILabel()
        aduValueLab.text = String(format: "￥%.2f x%d", self.stock!.adultPrice,self.num1)
        aduValueLab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        aduValueLab.textColor = UIColor.init(hexString: "#999999")
        bg2.addSubview(aduValueLab)
        let _  = aduValueLab.sd_layout()?.rightSpaceToView(bg2,56)!.heightIs(20)!.topSpaceToView(bg2,60)!
        aduValueLab.setSingleLineAutoResizeWithMaxWidth(166)
        
        let childLab = UILabel()
        childLab.text = "儿童"
        childLab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        childLab.textColor = UIColor.init(hexString: "#999999")
        bg2.addSubview(childLab)
        let _  = childLab.sd_layout()?.leftSpaceToView(bg2,56)!.heightIs(20)!.topSpaceToView(aduLab,16)!.widthIs(45)
        
        let childValueLab = UILabel()
        childValueLab.text = String(format: "￥%.2f x%d", self.stock!.childPrice,self.num2)
        childValueLab.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight(rawValue: 0.2))
        childValueLab.textColor = UIColor.init(hexString: "#999999")
        bg2.addSubview(childValueLab)
        let _  = childValueLab.sd_layout()?.rightSpaceToView(bg2,56)!.heightIs(20)!.topSpaceToView(aduLab,16)!
        childValueLab.setSingleLineAutoResizeWithMaxWidth(166)
        
        if self.num2 == 0 {
            
            childLab.isHidden = true
            childValueLab.isHidden = true
        }
        

        
        let payBtn = UIButton()
                   bg.addSubview(payBtn)
                   payBtn.addTarget(self, action: #selector(commitClick), for: .touchUpInside)
                   payBtn.sd_cornerRadius = LARAGE_BTN_RADIUS
                   let _ = payBtn.sd_layout()?.widthIs(164)?.heightIs(LARAGE_BTN_HEIGHT)?.rightSpaceToView(bg,10)?.centerYEqualToView(bg)
                   payBtn.gradientBtnMainColor()
                   
                   let tlab = UILabel()
                   tlab.text = "确定"
                   tlab.font = UIFont.commonFontSmall
                   tlab.textColor = UIColor.white
                   tlab.textAlignment = .center
                   payBtn.addSubview(tlab)
                   let _ = tlab.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
                   
                   let priceBtn = UIButton()
                   priceBtn.setTitle("总价:", for: .normal)
                   priceBtn.titleLabel?.font = UIFont.commonFont
                   priceBtn.setTitleColor(UIColor.tabbarDefaultTextColor, for: .normal)
                   priceBtn.addTarget(self, action: #selector(infoHideClick), for: .touchUpInside)
                   bg.addSubview(priceBtn)
                   let _ = priceBtn.sd_layout()?.leftSpaceToView(bg,16)?.centerYEqualToView(bg)!.widthIs(125)!.heightIs(35)
                   let _ =  priceBtn.titleLabel?.sd_layout()?.leftSpaceToView(priceBtn,0)!.heightIs(20)!.widthIs(45)!.centerYEqualToView(priceBtn)
        


                   
        let myprilb = UILabel()
                   priceBtn.addSubview(myprilb)
                   myprilb.font = UIFont.commonFont
                   myprilb.textColor = UIColor.GP_Orange_Color
            myprilb.text = self.allPrice
                   let _  =  myprilb.sd_layout()?.leftSpaceToView(priceBtn,40)!.heightIs(20)!.centerYEqualToView(priceBtn)
                   myprilb.setSingleLineAutoResizeWithMaxWidth(155)
               
                   let icon = UIImageView()
                   icon.image = UIImage(named: "向下")
                   priceBtn.addSubview(icon)
                   let _  =  icon.sd_layout()?.widthIs(16)!.heightIs(16)!.leftSpaceToView(self.priceLab,3)!.bottomSpaceToView(priceBtn,8)
                   

    }

    @objc func infoHideClick(){
        
        self.pricebg.removeFromSuperview()
    }
    
}
